﻿using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Newtonsoft.Json;

namespace WebAppIdentity
{
	public class RsaKeyManager
	{
		public void GenerateAndSaveRsaKeys(IWebHostEnvironment env)
		{
			var dir = Path.Combine(env.ContentRootPath, "Rsa");
			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir);
			}
			if (File.Exists(Path.Combine(dir, "key.private.json"))
				&& File.Exists(Path.Combine(dir, "key.public.json")))
			{
				return;
			}

			RSAParameters privateKey, publicKey;

			using (var rsa = RSA.Create(2048))
			{
				// 导出私钥
				privateKey = rsa.ExportParameters(true);


				// 导出公钥
				publicKey = rsa.ExportParameters(false);
			}
			File.WriteAllText(Path.Combine(dir, "key.public.json"), JsonConvert.SerializeObject(publicKey));
			File.WriteAllText(Path.Combine(dir, "key.private.json"), JsonConvert.SerializeObject(privateKey));
		}
	}
}
